package org.dromara.common.pdf.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.dromara.common.pdf.config.FileDirConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class QRUtils {


    public static String qrout(String content) throws Exception{
        File file = new File(FileDirConfig.FILE_TEMP);
        if (!file.exists()){
            file.mkdirs();
        }
        //生成二维码
        int width = 200;
        int height = 200;
        Map<EncodeHintType, Object> config = new HashMap<>();
        config.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        config.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, config);

        String guid = IdUtils.fastUUID();
        String path = FileDirConfig.FILE_TEMP+ guid;
        OutputStream out = new FileOutputStream(new File(path));
        MatrixToImageWriter.writeToStream(bitMatrix,"png",out);
        out.close();
        return path ;
    }

    public static String getQrCode(String content) throws Exception {
        // Create a new file object for the temporary directory
        File file = new File(FileDirConfig.FILE_TEMP);
        if (!file.exists()) {
            // Create the directory if it does not exist
            file.mkdirs();
        }

        // Generate QR code
        int width = 200;
        int height = 200;
        Map<EncodeHintType, Object> config = new HashMap<>();
        config.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        config.put(EncodeHintType.MARGIN, 0);

        // Encode the content to a BitMatrix
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, config);
        String guid = IdUtils.fastUUID();
        String path = FileDirConfig.FILE_TEMP + guid;
        OutputStream out = new FileOutputStream(new File(path));
        // Write the BitMatrix to a file as a PNG image
        MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
        out.close();
        return path;
    }

}
